﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using Communication.Channel;
using Communication.Message.FpgaUpdate;
using Vosc.Coff;
using Vosc.Logging;

namespace Vosc
{
	// Token: 0x02000013 RID: 19
	public partial class DspUpdateForm : Form
	{
		// Token: 0x0600007A RID: 122 RVA: 0x00009157 File Offset: 0x00007357
		public DspUpdateForm()
		{
			this.InitializeComponent();
		}

		// Token: 0x0600007B RID: 123 RVA: 0x00009168 File Offset: 0x00007368
		public DspUpdateForm(Channel channel, FlashUpdateType updateTarget, bool isUpdateKernal, Coffile coffile) : this()
		{
			this.channel = channel;
			this.updateTarget = updateTarget;
			this.isUpdateKernal = isUpdateKernal;
			this.coffile = coffile;
			this.runStatus = DspUpdateForm.RunStatus.Running;
			this.Text = string.Format("{0} 正在升级...", Enum.GetName(typeof(FlashUpdateType), updateTarget));
			this.buttonOK.Enabled = false;
		}

		// Token: 0x0600007C RID: 124 RVA: 0x000091D0 File Offset: 0x000073D0
		private void FpgaUpdateForm_Shown(object sender, EventArgs e)
		{
			Delegate method = new EventHandler(this.Update);
			object[] args = new object[2];
			base.BeginInvoke(method, args);
		}

		// Token: 0x0600007D RID: 125 RVA: 0x000091F8 File Offset: 0x000073F8
		private void Update(object obj, EventArgs arg)
		{
			try
			{
				FlashUpdateChannelMessage.totalSendByte = 0L;
				FlashUpdateChannelMessage.totalReceiveByte = 0L;
				int i = 0;
				this.labelTip.Text = "正在请求升级...";
				Application.DoEvents();
				NormalMessage message = new NormalMessage((byte)this.updateTarget, 0, null, 0, 0, 10000, 10000, 500);
				this.channel.WriteSync(message);
				this.labelTip.Text = "正在握手...";
				Application.DoEvents();
				for (i = 0; i < 3; i++)
				{
					SendHandshakeMessage sendHandshakeMessage = new SendHandshakeMessage((byte)this.updateTarget, 1, 1000, 1000, 500);
					this.channel.WriteSync(sendHandshakeMessage);
					if (sendHandshakeMessage.IsSuccess() && sendHandshakeMessage.ErrorCode == FlashUpdateErrorCode.SUCCESS)
					{
						this.WriteLog(sendHandshakeMessage);
						break;
					}
					this.WriteLog(sendHandshakeMessage);
				}
				if (i >= 3)
				{
					this.labelTip.Text = "握手失败";
				}
				else
				{
					this.labelTip.Text = "正在解锁芯片...";
					Application.DoEvents();
					for (i = 0; i < 3; i++)
					{
						NormalMessage normalMessage = new NormalMessage((byte)this.updateTarget, 2, null, 0, 0, 5000, 5000, 500);
						this.channel.WriteSync(normalMessage);
						if (normalMessage.IsSuccess() && normalMessage.ErrorCode == FlashUpdateErrorCode.SUCCESS)
						{
							this.WriteLog(normalMessage);
							break;
						}
						this.WriteLog(normalMessage);
					}
					if (i >= 3)
					{
						this.labelTip.Text = "芯片解锁失败";
					}
					else
					{
						this.labelTip.Text = "正在检测Flash API版本是否匹配...";
						Application.DoEvents();
						i = 0;
						while (i < 3)
						{
							NormalMessage normalMessage2 = new NormalMessage((byte)this.updateTarget, 3, null, 0, 0, 1000, 1000, 500);
							this.channel.WriteSync(normalMessage2);
							if (normalMessage2.IsSuccess())
							{
								if (normalMessage2.ErrorCode == FlashUpdateErrorCode.DSP_FLASH_API_VERSION_MATCH)
								{
									this.WriteLog(normalMessage2);
									break;
								}
								this.WriteLog(normalMessage2);
								this.labelTip.Text = "Flash API版本不匹配";
								return;
							}
							else
							{
								this.WriteLog(normalMessage2);
								i++;
							}
						}
						if (i >= 3)
						{
							this.labelTip.Text = "Flash API版本不匹配";
						}
						else
						{
							this.labelTip.Text = "正在擦除...";
							this.progressBar.Style = ProgressBarStyle.Marquee;
							Application.DoEvents();
							i = 0;
							while (i < 3)
							{
								var data = 6;
                                if (isUpdateKernal)
                                {
                                    data = 6;
                                }
                                else
                                {
									data = 5;
                                }

                                NormalMessage normalMessage3 = new NormalMessage((byte)this.updateTarget, 4, new byte[]
								{
                                    (byte)data
                                }, 1, 0, 30000, 30000, 500);
								this.channel.WriteAsync(normalMessage3);
								while (!normalMessage3.IsDone())
								{
									try
									{
										Application.DoEvents();
										Thread.Sleep(100);
									}
									catch
									{
									}
								}
								if (normalMessage3.IsSuccess())
								{
									if (normalMessage3.ErrorCode != FlashUpdateErrorCode.SUCCESS)
									{
										this.WriteLog(normalMessage3);
										this.progressBar.Style = ProgressBarStyle.Blocks;
										this.labelTip.Text = "擦除失败";
										return;
									}
									this.WriteLog(normalMessage3);
									break;
								}
								else
								{
									this.WriteLog(normalMessage3);
									i++;
								}
							}
							if (i >= 3)
							{
								this.progressBar.Style = ProgressBarStyle.Blocks;
								this.labelTip.Text = "擦除失败";
							}
							else
							{
								this.labelTip.Text = "正在检测是否可编程...";
								Application.DoEvents();
								for (i = 0; i < 3; i++)
								{
									NormalMessage normalMessage4 = new NormalMessage((byte)this.updateTarget, 5, null, 0, 0, 1000, 1000, 500);
									this.channel.WriteSync(normalMessage4);
									if (normalMessage4.IsSuccess() && normalMessage4.ErrorCode == FlashUpdateErrorCode.DSP_PROGRAM_ALLOW)
									{
										this.WriteLog(normalMessage4);
										break;
									}
									this.WriteLog(normalMessage4);
								}
								if (i >= 3)
								{
									this.labelTip.Text = "芯片不允许编程";
								}
								else
								{
									int blockCount = this.coffile.GetBlockCount(128);
									this.labelTip.Text = "正在编程...";
									this.progressBar.Style = ProgressBarStyle.Blocks;
									Application.DoEvents();
									this.progressBar.Maximum = blockCount;
									this.progressBar.Minimum = 0;
									this.progressBar.Step = 1;
									this.progressBar.Value = 0;
									Application.DoEvents();
									foreach (CoffSection coffSection in this.coffile.Sections)
									{
										int j = 0;
										int num = 0;
										while (j < (int)coffSection.Size)
										{
											if (num >= 3)
											{
												this.labelTip.Text = "编程失败——发送块重试";
												return;
											}
											short num2 = (short)(((int)coffSection.Size - j > 128) ? 128 : ((short)((int)coffSection.Size - j)));
											uint num3 = coffSection.StartAddress + (uint)j;
											byte[] array = new byte[6];
											this.writeShortToByteArray(array, 0, num2);
											this.writeIntToByteArray2(array, 2, (int)num3);
											byte[] array2 = new byte[(int)(num2 * 2)];
											for (int k = 0; k < (int)num2; k++)
											{
												this.writeShortToByteArray(array2, k * 2, (short)coffSection.Contents[j + k]);
											}
											i = 0;
											while (i < 3)
											{
												NormalMessage normalMessage5 = new NormalMessage((byte)this.updateTarget, 6, array, array.Length, 0, 1000, 1000, 500);
												this.channel.WriteSync(normalMessage5);
												if (normalMessage5.IsSuccess())
												{
													if (normalMessage5.ErrorCode != FlashUpdateErrorCode.SUCCESS)
													{
														this.WriteLog(normalMessage5);
														this.labelTip.Text = "编程失败——数据块索引返回码错误";
														return;
													}
													this.WriteLog(normalMessage5);
													break;
												}
												else
												{
													this.WriteLog(normalMessage5);
													i++;
												}
											}
											if (i >= 3)
											{
												this.labelTip.Text = "编程失败——数据块索引重试";
												return;
											}
											SendDataMessage sendDataMessage = new SendDataMessage((byte)this.updateTarget, 7, array2, array2.Length, 0, 2000, 2000, 2000);
											this.channel.WriteSync(sendDataMessage);
											this.WriteLog(sendDataMessage);
											Thread.Sleep(50);
											uint data = this.Sum32Check((ushort)num2, num3, coffSection.Contents, j);
											byte[] array3 = new byte[4];
											this.writeIntToByteArray2(array3, 0, (int)data);
											bool flag = false;
											for (i = 0; i < 3; i++)
											{
												NormalMessage normalMessage6 = new NormalMessage((byte)this.updateTarget, 8, array3, array3.Length, 0, 1000, 1000, 500);
												this.channel.WriteSync(normalMessage6);
												if (!normalMessage6.IsSuccess())
												{
													this.WriteLog(normalMessage6);
												}
												else
												{
													if (normalMessage6.ErrorCode == FlashUpdateErrorCode.DSP_PROGRAM_SUM_CHECK_OK)
													{
														this.WriteLog(normalMessage6);
														break;
													}
													if (normalMessage6.ErrorCode == FlashUpdateErrorCode.DSP_PROGRAM_SUM_CHECK_ERROR)
													{
														this.WriteLog(normalMessage6);
														num++;
														flag = true;
														break;
													}
												}
											}
											if (i >= 3)
											{
												this.labelTip.Text = "编程失败——校验重试";
												return;
											}
											if (!flag)
											{
												flag = false;
												for (i = 0; i < 3; i++)
												{
													NormalMessage normalMessage7 = new NormalMessage((byte)this.updateTarget, 9, null, 0, 0, 1000, 1000, 500);
													this.channel.WriteSync(normalMessage7);
													if (!normalMessage7.IsSuccess())
													{
														this.WriteLog(normalMessage7);
													}
													else
													{
														if (normalMessage7.ErrorCode == FlashUpdateErrorCode.SUCCESS)
														{
															this.WriteLog(normalMessage7);
															break;
														}
														if (normalMessage7.ErrorCode == FlashUpdateErrorCode.DSP_PROGRAM_BLOCK_ADDRESS_OUT_OF_RANGE_OR_PROGRAM_BLOCK_SIZE_OUT_OF_RANGE_OR_PROGRAM_STATUS_FAILED)
														{
															this.WriteLog(normalMessage7);
														}
														else if (normalMessage7.ErrorCode == FlashUpdateErrorCode.DSP_PROGRAM_STATUS_FAIL_ZERO_BIT_ERROR)
														{
															this.WriteLog(normalMessage7);
															num++;
															flag = true;
															break;
														}
													}
												}
												if (i >= 3)
												{
													this.labelTip.Text = "编程失败——确认编程状态重试";
													return;
												}
												if (!flag)
												{
													for (i = 0; i < 3; i++)
													{
														NormalMessage normalMessage8 = new NormalMessage((byte)this.updateTarget, 10, null, 0, 0, 1000, 1000, 500);
														this.channel.WriteSync(normalMessage8);
														if (!normalMessage8.IsSuccess())
														{
															this.WriteLog(normalMessage8);
														}
														else
														{
															if (normalMessage8.ErrorCode == FlashUpdateErrorCode.SUCCESS)
															{
																this.WriteLog(normalMessage8);
																j += (int)num2;
																this.progressBar.Value++;
																num = 0;
																Application.DoEvents();
																Thread.Sleep(5);
																break;
															}
															if (normalMessage8.ErrorCode == FlashUpdateErrorCode.DSP_PROGRAM_STATUS_FAIL_VERIFY)
															{
																this.WriteLog(normalMessage8);
																num++;
																break;
															}
														}
													}
													if (i >= 3)
													{
														this.labelTip.Text = "编程失败——DSP校验重试";
														return;
													}
												}
											}
										}
									}
									this.labelTip.Text = "正在结束升级...";
									Application.DoEvents();
									for (i = 0; i < 3; i++)
									{
										byte desId = (byte)this.updateTarget;
										byte funCode = 6;
										byte[] datas = new byte[6];
										NormalMessage normalMessage9 = new NormalMessage(desId, funCode, datas, 6, 0, 1000, 1000, 500);
										this.channel.WriteSync(normalMessage9);
										if (normalMessage9.IsSuccess())
										{
											if (normalMessage9.ErrorCode == FlashUpdateErrorCode.DSP_PROGRAM_END_OF_FILE)
											{
												this.WriteLog(normalMessage9);
												this.labelTip.Text = "升级成功";
												this.progressBar.Value = this.progressBar.Maximum;
												break;
											}
											this.WriteLog(normalMessage9);
										}
										else
										{
											this.WriteLog(normalMessage9);
										}
									}
									if (i >= 3)
									{
										this.labelTip.Text = "结束升级失败";
									}
									else
									{
										InternalLoggerFactory.Logger.Error(string.Format("总发送字节数{0}，总接收字节数{1}。", FlashUpdateChannelMessage.totalSendByte.ToString(), FlashUpdateChannelMessage.totalReceiveByte.ToString()));
									}
								}
							}
						}
					}
				}
			}
			catch (Exception exception)
			{
				this.labelTip.Text = "升级过程中出现未能识别的错误";
				InternalLoggerFactory.Logger.Error("升级过程中出现未能识别的错误", exception);
			}
			finally
			{
				this.buttonOK.Enabled = true;
				this.runStatus = DspUpdateForm.RunStatus.Stoped;
			}
		}

		// Token: 0x0600007E RID: 126 RVA: 0x00009BD8 File Offset: 0x00007DD8
		private uint Sum32Check(ushort blocksize, uint blockAddr, ushort[] blockData, int offset)
		{
			uint num = 0u;
			num += (uint)blocksize;
			num += blockAddr;
			for (int i = 0; i < (int)blocksize; i++)
			{
				num += (uint)blockData[offset + i];
			}
			return num;
		}

		// Token: 0x0600007F RID: 127 RVA: 0x00009C08 File Offset: 0x00007E08
		private void WriteLog(FlashUpdateChannelMessage msg)
		{
			if (msg == null)
			{
				return;
			}
			if (!msg.IsDone())
			{
				return;
			}
			if (msg.GetCause() == null)
			{
				InternalLoggerFactory.Logger.Error(string.Format("write message [{0}] —— desid={1}, funcode={2}, errorcode={3}, sendmsg:{4}, receivemsg:{5}", new object[]
				{
					msg.GetType().FullName,
					msg.DesId.ToString("X2"),
					msg.FunCode.ToString("X2"),
					msg.ErrorCode.ToString(),
					msg.HexDumpSendMessage(),
					msg.HexDumpReceiveMessage()
				}));
				return;
			}
			InternalLoggerFactory.Logger.Error(string.Format("write message [{0}] error —— desid={1}, funcode={2}, errorcode={3}, sendmsg:{4}, receivemsg:{5}", new object[]
			{
				msg.GetType().FullName,
				msg.DesId.ToString("X2"),
				msg.FunCode.ToString("X2"),
				msg.ErrorCode.ToString(),
				msg.HexDumpSendMessage(),
				msg.HexDumpReceiveMessage()
			}), msg.GetCause());
		}

		// Token: 0x06000080 RID: 128 RVA: 0x00009D29 File Offset: 0x00007F29
		private void buttonOK_Click(object sender, EventArgs e)
		{
			base.Close();
		}

		// Token: 0x06000081 RID: 129 RVA: 0x00009D31 File Offset: 0x00007F31
		private void FlashUpdateForm_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (this.runStatus == DspUpdateForm.RunStatus.Running)
			{
				e.Cancel = true;
			}
		}

		// Token: 0x06000082 RID: 130 RVA: 0x00009D42 File Offset: 0x00007F42
		private int writeShortToByteArray(byte[] byteArray, int offset, short data)
		{
			byteArray[offset] = (byte)(data >> 8);
			byteArray[offset + 1] = (byte)(data & 255);
			return 2;
		}

		// Token: 0x06000083 RID: 131 RVA: 0x00009D59 File Offset: 0x00007F59
		private int writeIntToByteArray(byte[] byteArray, int offset, int data)
		{
			byteArray[offset] = (byte)(data >> 24);
			byteArray[offset + 1] = (byte)(data >> 16);
			byteArray[offset + 2] = (byte)(data >> 8);
			byteArray[offset + 3] = (byte)data;
			return 4;
		}

		// Token: 0x06000084 RID: 132 RVA: 0x00009D7E File Offset: 0x00007F7E
		private int writeIntToByteArray2(byte[] byteArray, int offset, int data)
		{
			byteArray[offset] = (byte)(data >> 8);
			byteArray[offset + 1] = (byte)data;
			byteArray[offset + 2] = (byte)(data >> 24);
			byteArray[offset + 3] = (byte)(data >> 16);
			return 4;
		}

		// Token: 0x040000AC RID: 172
		private Channel channel;

		// Token: 0x040000AD RID: 173
		private FlashUpdateType updateTarget;

		// Token: 0x040000AE RID: 174
		private bool isUpdateKernal;

		// Token: 0x040000AF RID: 175
		private Coffile coffile;

		// Token: 0x040000B0 RID: 176
		private DspUpdateForm.RunStatus runStatus;

		// Token: 0x02000014 RID: 20
		private enum RunStatus
		{
			// Token: 0x040000B6 RID: 182
			Running,
			// Token: 0x040000B7 RID: 183
			Stoped
		}
	}
}
